local major, minor = "RCE", "r64"

local lib, oldMinor = LibStub:NewLibrary(major, minor)
if not lib then return end

if not lib.frame then
	lib.frame = CreateFrame("Frame")
	lib.frame.name = "RCE Frame"
	lib.frame:Hide()
end

if not lib.embeds then
	lib.embeds = {}
end

local type = type
local select = select
local error = error
local pairs = pairs
local pcall = pcall

local mixins = {
	"RegisterCombatEvent",
	"RegisterCombatEvents",
	"IsCombatEventRegistered",
}

function lib:HandleCombatEvent(self, time, eventType, ...)
	for object, data in pairs(lib.embeds) do
		if data[eventType] then
			local sucess, error = pcall(data[eventType], object, ...)
			if not sucess then
				geterrorhandler()(error)
			end
		end
	end
end

function lib:Embed(object)
	for _, func in ipairs(mixins) do
		object[func] = lib[func]
	end
	lib.embeds[object] = {}
end

function lib:RegisterCombatEvent(event, func)
	if not lib.embeds[self] then
		lib.embeds[self] = {}
	end
	lib.embeds[self][event] = func
end

function lib:RegisterCombatEvents(...)
	if not lib.embeds[self] then
		lib.embeds[self] = {}
	end
	
	local func
	local numArgs = select("#", ...)
	if type(select(numArgs, ...)) == "function" then
		func = select(numArgs, ...)
	else
		error(format("bad argument #"..numArgs.." to 'RegisterCombatEvents' (function expected, got %s)", type(select(numArgs, ...))))
	end	

	for i=1, (numArgs - 1) do
		if type(select(i, ...)) == "string" then
			lib.embeds[self][select(i, ...)] = func
		end
	end
end

function lib:IsCombatEventRegistered(event)
	if lib.embeds[self] and lib.embeds[self][event] then
		return true
	end
	return false
end
	
lib.frame:RegisterEvent("COMBAT_LOG_EVENT_UNFILTERED")
lib.frame:SetScript("OnEvent", lib.HandleCombatEvent)